﻿using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Spire.PdfViewer.Forms;
using Sunny.UI;
using Sunny.UI.Win32;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Web;
using WinApp.i18n;
using WinApp.Until;
using WinApp.ViewModel;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace WinApp.View
{
    public partial class CbtPlay : UserControl
    {

        public WinApp _parent { get; set; }

        //WebBrowser _webBrowserLms;  貌似是ie内核不支持
        private Microsoft.Web.WebView2.WinForms.WebView2 _webView2;

        private PdfDocumentViewer _pdfViewer;

        public CbtPlayInputDto _inputDto { get; set; }
        public CbtPlay()
        {
            InitializeComponent();


            // 创建WebView2实例
            _webView2 = new Microsoft.Web.WebView2.WinForms.WebView2();
            // 设置Dock样式为Fill，使其填充整个窗体或指定的Panel等控件
            _webView2.Dock = DockStyle.Fill;
            _webView2.NavigationCompleted += _webView2_NavigationCompleted;
            // 将WebView2添加到窗体上（这里假设有一个名为panel1的Panel）
            this.panel2.Controls.Add(_webView2);
            // 初始化WebView2环境
            InitializeAsync();

            _pdfViewer = new PdfDocumentViewer();
            _pdfViewer.Dock = DockStyle.Fill;
            this.panel2.Controls.Add(_pdfViewer);

            //_vlcControl = new VlcControl();
            //_vlcControl.Dock = DockStyle.Fill;
            //this.panel2.Controls.Add(_vlcControl);
        }

        private async void _webView2_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            if (_inputDto.CourseUnitType == 5)
            {
                // 禁止自动播放
                await _webView2.ExecuteScriptAsync("document.querySelector('video').autoplay = false;");

                // 执行JavaScript代码获取视频长度
                string strTotal = await _webView2.ExecuteScriptAsync("document.querySelector('video').duration");
                double.TryParse(strTotal, out double videoTotal);
                int roundedNumber = (int)Math.Round(videoTotal, MidpointRounding.AwayFromZero);
                _inputDto.TotalCount = roundedNumber;

                var Mp4Data = CbtPlayModel.ReadMp4Data(_inputDto.LearningStatuTableId);
                if (Mp4Data.CurrentProgress > 0)
                {
                    if (UtilHelper.ShowAskDialog("你已经学习了" + Mp4Data.CurrentProgress + "是否指定位置学习？"))
                    {
                        await _webView2.ExecuteScriptAsync($"document.querySelector('video').currentTime = {Mp4Data.CurrentProgress};");//从第10秒开始                            
                                                                                                                                        // 禁止自动播放
                    }
                    else
                    {
                        await _webView2.ExecuteScriptAsync($"document.querySelector('video').currentTime = {0};");

                    }
                }
                await _webView2.ExecuteScriptAsync("document.querySelector('video').play();");
            }
        }

        private async void InitializeAsync()
        {
            // 确保CoreWebView2运行时已准备就绪
            await _webView2.EnsureCoreWebView2Async();


            // 加载百度首页
            //await LoadBaiduHomePageAsync();
        }

        private async Task LoadBaiduHomePageAsync()
        {

        }

        protected override async void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // 如果需要在窗体加载完成后再初始化和加载网页，可以在这里调用InitializeAsync方法
            // await InitializeAsync();
            // await LoadBaiduHomePageAsync();
        }

        private void CbtPlay_Load(object sender, EventArgs e)
        {
            _webView2.CoreWebView2.NavigationStarting += async (sender, args) =>
            {
                //await webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("sessionStorage.setItem('key', 'value');");

                var token = string.IsNullOrWhiteSpace(WebApiHelper._Authorization) ? "" : WebApiHelper._Authorization;
                Dictionary<string, string> tokenDic = new Dictionary<string, string>();
                tokenDic.Add("token", token);

                string jsString1 = string.Format("sessionStorage.setItem('refresh_token', '{0}')", WebApiHelper._RefreshToken);
                await _webView2.CoreWebView2.ExecuteScriptAsync(jsString1);

                string jsString = string.Format("sessionStorage.setItem('_token', '{0}')", JsonConvert.SerializeObject(tokenDic));
                await _webView2.CoreWebView2.ExecuteScriptAsync(jsString);


            };

            //_webView2.CoreWebView2.NewWindowRequested += (sender, args) =>
            //{
            //    // 将新窗口的请求地址设置为当前WebView的地址，这将在同一个WebView中打开链接
            //    _webView2.Source = new Uri(args.Uri);
            //    // 设置Handled属性为true，表示我们已经处理了这个事件，阻止WebView2打开新窗口
            //    args.Handled = true;
            //};
        }

        public async void LoadCbtPlay()
        {

            _webView2.Visible = false;
            _pdfViewer.Visible = false;
            //_vlcControl.Visible = false;


            var host = GlobalVariables.HostIp;
            var webIp = GlobalVariables.WebIp;
            var langType = GlobalVariables.SystemLanguage == LanguageType.English ? "en-US" : "zh-CN";

            var timeStamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            string playUrl = string.Empty;


            var token = string.IsNullOrWhiteSpace(WebApiHelper._Authorization) ? "" : WebApiHelper._Authorization;
            Dictionary<string, string> tokenDic = new Dictionary<string, string>();
            tokenDic.Add("token", token);
            var valueStr = HttpUtility.UrlEncode(JsonConvert.SerializeObject(tokenDic), Encoding.UTF8);
            //+号替换成空格（HttpUtility.UrlEncode会将空格转换成+号）
            valueStr = valueStr.Replace("+", "%20");
            //原来是+号的还原
            valueStr = valueStr.Replace("%2b", "+");

            var cookieManager = _webView2.CoreWebView2.CookieManager;
            CoreWebView2Cookie cookie2 = cookieManager.CreateCookie("refresh_token", WebApiHelper._RefreshToken, GlobalVariables.RootDomainName, "/");
            cookie2.SameSite = CoreWebView2CookieSameSiteKind.Lax;
            //cookie2.IsSecure = true;
            cookieManager.AddOrUpdateCookie(cookie2);
            //_inputDto.CourseUnitType = 5;
            switch (_inputDto.CourseUnitType)
            {
                case 1:
                    _pdfViewer.Visible = true;

                    string filePath = GlobalVariables.WebIp + _inputDto.CourseUnitLanuchPath;
                    // 使用 HttpClient 下载 PDF 文件
                    using (HttpClient client = new HttpClient())
                    {
                        byte[] pdfBytes = await client.GetByteArrayAsync(filePath);

                        // 创建一个临时文件来保存 PDF
                        string tempFilePath = Path.GetTempFileName();
                        await File.WriteAllBytesAsync(tempFilePath, pdfBytes);

                        try
                        {

                            _pdfViewer.LoadFromFile(tempFilePath);
                            // For file size
                            FileInfo fileInfo = new FileInfo(tempFilePath);

                            string pdfUrl = "http://example.com/path/to/your.pdf";
                            Uri uri = new Uri(pdfUrl);
                            string filename = Path.GetFileName(uri.LocalPath);

                            _inputDto.StudyName = filename;
                            _inputDto.TotalSize = fileInfo.Length;
                            _inputDto.TotalCount = _pdfViewer.PageCount;

                        }
                        finally
                        {
                            // 无论处理过程是否成功，都尝试删除临时文件
                            try
                            {
                                File.Delete(tempFilePath);
                            }
                            catch
                            {
                                // 忽略删除文件过程中的错误
                            }
                        }
                    }
                    break;

                case 2:
                case 3:

                    _webView2.Visible = true;
                    if (_webView2 == null || _webView2.CoreWebView2 == null)
                    {
                        UIMessageDialog.ShowMessageDialog(Language.GetLang("notFindWebView"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                        return;
                    }
                    playUrl = webIp + $"traineecenter/assets/scorm/player.html?r={timeStamp}" +
                        $"&language={langType}" +
                        $"&tenancy={WebApiHelper._Tenancy}" +
                        $"&host={host}" +
                        $"&CourseUnitType={_inputDto.CourseUnitType}" +
                        $"&lanuch={webIp + _inputDto.CourseUnitLanuchPath}" +
                        $"&LessonAttemptedId={_inputDto.LessonAttemptedId}" +
                        $"&LearningStatuTableId={_inputDto.LearningStatuTableId}" +
                        $"&StructureId={_inputDto.StructureId}" +
                        $"&EnrollmentId={_inputDto.EnrollmentId}" +
                        $"&CourseId={_inputDto.CourseId}" +
                        $"&CourseUnitId={_inputDto.CourseUnitId}" +
                        $"&IsCheckReferer=true";


                    //string baiduUrl = "https://www.baidu.com";
                    _webView2.CoreWebView2.Navigate(playUrl);

                    break;
                case 4:
                case 5:
                    _webView2.Visible = true;
                    var mp4FileName = GlobalVariables.WebIp + _inputDto.CourseUnitLanuchPath;
                    //mp4FileName = @"http://vjs.zencdn.net/v/oceans.mp4";
                    //string pdfUrl = "http://example.com/path/to/your.pdf";

                    Uri videoUri = new Uri(mp4FileName);
                    string videoFilename = Path.GetFileName(videoUri.LocalPath);
                    _inputDto.StudyName = videoFilename;
                    //获取mp4 资源大小
                    _inputDto.TotalSize = FileHelper.GetWebFileSize(mp4FileName);

                    _webView2.CoreWebView2.Navigate(mp4FileName);

                    break;
                case 7:

                    _webView2.Visible = true;

                    if (_webView2 == null || _webView2.CoreWebView2 == null)
                    {
                        UIMessageDialog.ShowMessageDialog(Language.GetLang("notFindWebView"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                        return;
                    }

                    playUrl = webIp + $"traineecenter/assets/scorm/SCORM12player.html?r={timeStamp}" +
                        $"&language={langType}" +
                        $"&tenancy={WebApiHelper._Tenancy}" +
                        $"&host={host}" +
                        $"&lanuch={webIp + "/" + _inputDto.CourseUnitLanuchPath}" +
                        $"&CourseUnitType={_inputDto.CourseUnitType}" +

                        $"&LessonAttemptedId={_inputDto.LessonAttemptedId}" +
                        $"&LearningStatuTableId={_inputDto.LearningStatuTableId}" +
                        $"&StructureId={_inputDto.StructureId}" +
                        $"&EnrollmentId={_inputDto.EnrollmentId}" +
                        $"&CourseUnitId={_inputDto.CourseUnitId}" +
                        $"&CourseUnitLanuchPath={webIp + _inputDto.CourseUnitLanuchPath}" +
                        $"&CourseName={_inputDto.StructureName}" +
                        $"&CourseId={_inputDto.CourseId}" +
                        $"&IsCheckReferer=true";

                    //string baiduUrl = "https://www.baidu.com";
                    _webView2.CoreWebView2.Navigate(playUrl);

                    break;
                default:
                    break;
            }


        }


        private async void btnBack_Click(object sender, EventArgs e)
        {
            //_webBrowserLms.Hide();
            if (_inputDto.CourseUnitType == 1)
            {
                _inputDto.CurrentProgress = _pdfViewer.CurrentPageNumber;

                var result = CbtPlayModel.SavePdfData(new AttemptedDetailPdfPutData()
                {
                    LessonAttemptedId = _inputDto.LessonAttemptedId,
                    LearningStatuTableId = _inputDto.LearningStatuTableId,
                    Message = string.Empty,

                    StudyName = _inputDto.StudyName,
                    CurrentProgress = _inputDto.CurrentProgress,
                    TotalCount = _inputDto.TotalCount,
                    TotalSize = _inputDto.TotalSize.ToString()
                }, _inputDto.EnrollmentId, _inputDto.StructureId);
                if (!result)
                {
                    UIMessageDialog.ShowMessageDialog(Language.GetLang("error_SavePdfData"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                    return;
                }
            }

            if (_inputDto.CourseUnitType == 5)
            {
                // 执行 JavaScript 代码获取视频当前播放进度
                string currentTimeResultStr = await _webView2.ExecuteScriptAsync("document.querySelector('video').currentTime");
                double.TryParse(currentTimeResultStr, out double currentTimeResult);
                int currentTimeNumber = (int)Math.Round(currentTimeResult, MidpointRounding.AwayFromZero);
                _inputDto.CurrentProgress = currentTimeNumber;//当前视频播放位置

                var result = CbtPlayModel.SavePdfData(new AttemptedDetailPdfPutData()
                {
                    LessonAttemptedId = _inputDto.LessonAttemptedId,
                    LearningStatuTableId = _inputDto.LearningStatuTableId,
                    Message = string.Empty,

                    StudyName = _inputDto.StudyName,
                    CurrentProgress = _inputDto.CurrentProgress,
                    TotalCount = _inputDto.TotalCount,
                    TotalSize = _inputDto.TotalSize.ToString()
                }, _inputDto.EnrollmentId, _inputDto.StructureId);
                if (!result)
                {
                    UIMessageDialog.ShowMessageDialog(Language.GetLang("error_SavePdfData"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                    return;
                }
            }

            _inputDto = new CbtPlayInputDto();
            _webView2.Source = new Uri("about:blank");
            _parent.CloseCbtPlay();
        }
    }
}
